import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import 'echarts-wordcloud'; //词云图
import '@/utils/sdk'; //动态词云图 TagCanvas
import { defineComponent, h, onMounted, ref } from 'vue';
import { useResize } from '@/hooks';

export const useCharts = (name, options) => {
  return defineComponent({
    name: 'chart-' + name,
    setup() {
      const chartRef = ref();
      var myChart: ECharts;

      useResize(chartRef, () => {
        myChart.resize();
      });

      onMounted(() => {
        myChart = echarts.init(chartRef.value);

        myChart.setOption(options);
      });

      return () =>
        h('div', {
          ref: chartRef,
          class: 'chart-main'
        });
    }
  });
};

export const useTagCanvas = (name, options) => {
  return defineComponent({
    name: 'chart-' + name,
    setup() {
      const chartRef = ref();

      function startTagCanvas() {
        createCanvas();
        window['TagCanvas'].Start('rootcanvas', 'tags', {
          textColour: null,
          noSelect: true,
          initial: [0.02, 0.01],
          lock: 'xy',
          wheelZoom: false,
          minTags: 10,
          textHeight: 13
        });
      }

      function createCanvas() {
        const canvas = document.createElement('canvas');
        let el = chartRef.value;
        canvas.width = el.offsetWidth;
        canvas.height = el.offsetHeight;
        canvas.id = 'rootcanvas';
        el.appendChild(canvas);
      }

      function reportWindowSize() {
        const AppCanvas = chartRef.value.querySelector('#rootcanvas');
        if (AppCanvas.parentElement) {
          AppCanvas.parentElement.removeChild(AppCanvas);
        }
        startTagCanvas();
      }

      useResize(
        chartRef,
        () => {
          reportWindowSize();
        },
        {
          debounce: 300
        }
      );

      onMounted(() => {
        startTagCanvas();
      });

      return () =>
        h('div', { class: 'chart-main' }, [
          h(
            'div',
            {
              id: 'tags',
              style: 'display:none'
            },
            options.map((text) => {
              return h(
                'a',
                {
                  href: 'javascript:void(0);',
                  style: {
                    color:
                      '#' +
                      Math.floor(Math.random() * 0xffffff)
                        .toString(16)
                        .padEnd(6, '0')
                  }
                },
                text
              );
            })
          ),
          h('div', {
            id: 'chart-ref',
            style: 'width:100%;height:100%',
            ref: chartRef
          })
        ]);
    }
  });
};
